import { Context, EggAppConfig } from 'egg';

export default function authMiddleWare(options?: EggAppConfig['auth']): any {
  return async (ctx: Context, next: () => Promise<any>) => {
    // 获取客户端ip，过滤ipv6
    const ip = ctx.ip ? ctx.ip.replace(/::ffff:/, '') : '-';

    const dbIpDoc = await ctx.app[options.dbCluster].db(options.dbDB).collection(options.dbCollection)
      .findOne({ _id: ip });

    if (!dbIpDoc) {
      ctx.send403();
      return;
    }
    await next();
  };
}
